//
//  UINavigationController+TFCore.m
//  TFFoundation
//
//  Created by TFAppleWork-Summer on 2017/3/28.
//  Copyright © 2017年 TFAppleWork-Summer. All rights reserved.
//

#import "UINavigationController+TFCore.h"
#import "UIViewController+TFCore.h"

@implementation UINavigationController (TFCore)

- (void)tf_popToViewControllerWithClass:(Class)popClass animated:(BOOL)animated {
    NSArray *viewControllers = self.viewControllers;
    for (NSInteger i=0; i < viewControllers.count-1; i++) {
        UIViewController *viewController = viewControllers[i];
        if ([viewController isKindOfClass:popClass]) {
            [self popToViewController:viewController animated:animated];
            return;
        }
    }
}

- (void)tf_popToViewControllerWithCount:(NSUInteger)count animated:(BOOL)animated {
    NSArray *viewControllers = self.viewControllers;
    if (count>self.viewControllers.count-1) {
        return;
    }
    else {
        NSInteger popVCIndex = viewControllers.count - count - 1;
        [self popToViewController:viewControllers[popVCIndex] animated:animated];
    }
    
}

- (UIViewController *)tf_ViewControllerForClass:(Class)viewControllerClass {
    UIViewController *vc = nil;
    for (UIViewController *subVC in self.viewControllers) {
        if ([subVC isKindOfClass:viewControllerClass]) {
            vc = subVC;
            break;
        }
    }
    return vc;
}


- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
    if([self.viewControllers count] < [navigationBar.items count]) {
        return YES;
    }
    BOOL shouldPop = YES;
    UIViewController* vc = [self topViewController];
    if ([vc respondsToSelector:@selector(tf_shouldPopBack)]) {
        shouldPop = [vc tf_shouldPopBack];
    }
    if(shouldPop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.viewControllers.count>navigationBar.items.count) {
                [self popViewControllerAnimated:YES];
            }
        });
    }
    else {
        [self.navigationBar.subviews lastObject].alpha = 1.0;
    }
    return shouldPop;
}

@end
